iT邦幫忙

2022 iThome 鐵人賽

DAY 16
0
Modern Web

clojure 刷刷鍋系列 第 16

Clojure 肉片 -第 16 塊

  • 分享至 

  • xImage
  •  

【今日湯底】

My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!

In honor of my grandfather's memory we will write a function using his formula!

Take a list of ages when each of your great-grandparent died.
Multiply each number by itself.
Add them all together.
Take the square root of the result.
Divide by two.
Example
predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86
Note: the result should be rounded down to the nearest integer.

Some random tests might fail due to a bug in the JavaScript implementation. Simply resubmit if that happens to you.

(必須通過以下測試)

(ns predicter-test
  (:require [clojure.test :refer :all]
            [predicter :refer :all]))

(deftest predit-age-test1
  (is (= (predict-age 65 60 75 55 60 63 64 45) 86)))

(deftest predit-age-test2
  (is (= (predict-age 32 54 76 65 34 63 64 45) 79)))

【我的答案】

(ns predicter)
(defn predict-age [& age]
  (->> age
    (map #(* % %))
    (reduce +)
    (Math/sqrt)
    (* 0.5)
    (Math/floor)
    (int))
)

思路:

  1. 照著題目找合適的 function,發現很多數學計算在 clojure 都是借用 java interop

【其他人的答案】

(ns predicter)
(defn predict-age [& ages]
  (->> (map #(* % %) ages)
       (reduce +)
       (Math/sqrt)
       (#(/ % 2))
       int))

上一篇
Clojure 肉片 -第 15 塊
下一篇
Clojure 肉片 -第 17 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言